#ifndef SEM_POSIX_H_INCLUDE
#define SEM_POSIX_H_INCLUDE

#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>

#include <string>

using std::string;
#include "file_create_mode.h"

// link with -lpthread
enum SEM_RW
{
    SEM_READ    = O_RDONLY,
    SEM_WRITE   = O_WRONLY,
    SEM_RDWR    = O_RDWR,
    SEM_CREAT   = O_CREAT,
    SEM_EXECL   = O_EXCL
};

class CSem
{
public:
    CSem(const string& name,unsigned int initvalue = 1,
            int flags = SEM_RDWR|SEM_CREAT|SEM_EXECL,
            int mode = USER_R|USER_W|OTHER_R);
    ~CSem();
    
    bool open();

    bool isOpened();
    
    bool lock();
    bool trylock();
    bool timelock(unsigned int second);

    bool unlock();

    bool unlink();
    
private:
    CSem(const CSem& other);
    CSem& operator=(const CSem& other);

private:
    sem_t   *m_sem;
    string  m_name;
    unsigned int m_initvalue;
    int     m_flags;
    int     m_mode;
};

class CScopedSem
{
public:
    CScopedSem(CSem* psem):
        m_sem(psem)
    {
        if (m_sem != NULL)
            m_sem->lock();
    }
    
    ~CScopedSem()
    {
        if (m_sem != NULL)
            m_sem->unlock();
    }
private:
    CSem    *m_sem;
};

#endif








